<?php

namespace app\interactive\home;

use app\common\controller\Api;
use app\interactive\admin\Question;
use app\interactive\model\User as UserModel;
use app\interactive\model\Token as TokenModel;
use app\interactive\model\Question as QuestionModel;
use app\interactive\model\Active as ActiveModel;
use app\interactive\model\History as HistoryModel;


define('REMOTE_IP', '171.88.164.97');
define('REMOTE_PORT', 8800);

class User extends Api
{
    //登录
    public function Login()
    {
        $phone_num = $this->get_param('phoneNum');
        $name = $this->get_param('name');

        // 检查必要参数是否存在
        if (!isset($phone_num) || !isset($name)) {
            $this->api_echo(100, '缺少参数');
            return; // 添加return，避免继续执行后续代码
        }

        // 根据手机号查询用户
        $user = UserModel::where('userPhoneNum', $phone_num)->find();
        $token = md5($phone_num . mt_rand(10000, 99999) . time());
        $expire = time() + 3600 * 24 * 30;

        if ($user) {
            if ($user->name !== $name) {
                $this->api_echo(101, '用户信息不匹配');
                return; // 添加return，避免继续执行后续代码
            }
            $user_token = TokenModel::where(['user_id' => $user['id'], 'status' => 0])->where('expire', '>', time())->find();
            if (empty($user_token)) {
                $insert_arr = array(
                    'user_id' => $user['id'],
                    'token' => $token,
                    'expire' => $expire,
                    'create_t' => time(),
                    'status' => 0
                );
                TokenModel::insert($insert_arr);
            } else {
                $token = $user_token['token'];
            }
            $update_login_time['loginTime'] = time();
            UserModel::where(['id' => $user->id])->update($update_login_time);

            $histroyData = HistoryModel::where(['user_id' => $user->id])->column('active_id');

            $this->api_echo(200, '登录成功', ['user_id' => $user->id, 'token' => $token, 'name' => $user->name, 'joinHistory' => $histroyData]);
        } else {
            $new_user_data = array(
                'userPhoneNum' => $phone_num,
                'registerTime' => time(),
                'loginTime' => time(),
                'name' => $name,
                'status' => 0
            );

            $uid = UserModel::insertGetId($new_user_data); // 使用insertGetId获取新插入用户的ID
            $insert_arr = array(
                'user_id' => $user['id'],
                'token' => $token,
                'expire' => $expire,
                'create_t' => time(),
                'status' => 0
            );
            TokenModel::insert($insert_arr);
            $update_login_time['loginTime'] = time();
            UserModel::where(['id' => $uid])->update($update_login_time);
            $this->api_echo(200, '登录成功', ['user_id' => $uid, 'token' => $token, 'name' => $name, 'joinHistory' => []]);
        }
    }
    //获取题目
    public function getActiveQuestion()
    {
        $activeId = $this->get_param('id');

        // 检查必要参数是否存在
        if (empty($activeId)) {
            return $this->api_echo(100, '缺少参数');
        }

        // 查询数据库
        try {
            $questionData = QuestionModel::where(['activeId' => $activeId])
                ->order('id asc')
                ->select()
                ->toArray();
        } catch (\Exception $e) {
            return $this->api_echo(500, '数据库查询失败');
        }

        // 处理查询结果
        $data = array();

        foreach ($questionData as $key => $item) {
            $data[$key] = [
                'text' => $item['topic'],
                'answers' => [
                    $item['optionA'],
                    $item['optionB'],
                    $item['optionC'],
                    $item['optionD']
                ]
            ];

            switch ($item['correct']) {
                case 'A':
                    $data[$key]['correct'] = $item['optionA'];
                    break;
                case 'B':
                    $data[$key]['correct'] = $item['optionB'];
                    break;
                case 'C':
                    $data[$key]['correct'] = $item['optionC'];
                    break;
                case 'D':
                    $data[$key]['correct'] = $item['optionD'];
                    break;
            }
        }

        $return = array(
            'questions' => $data,
            'activeName' => ActiveModel::where('id', $activeId)->field('activeName')->find()['activeName']
        );
        // 返回处理后的数据
        return $this->api_echo(200, '成功', $return);
    }

    //上传答题记录
    public function uploadAnswerHistory()
    {
        $activeId = $this->get_param('activeId');
        $answer_right = $this->get_param('answerRight');

        // 检查必要参数是否存在
        if (empty($activeId)) {
            return $this->api_echo(100, '缺少参数');
        }



        $histroy = HistoryModel::where(['active_id' => $activeId, 'user_id' => $this->user_id])->find();

        if (empty($histroy)) {
            $newHistory =  array(
                'user_id' => $this->user_id,
                'active_id' => $activeId,
                'complete_time' => time()
            );

            if ($answer_right) {
                $newHistory['state'] = 1;
            } else {
                $newHistory['state'] = 0;
            }

            $res = HistoryModel::create($newHistory);

            if ($answer_right) {

                $user_integral = UserModel::where(['id' => $this->user_id])->select()->toArray();

                $update_intergral = array(
                    'integral' => $user_integral[0]['integral'] + 1
                );
                UserModel::where(['id' => $this->user_id])->update($update_intergral);
            }
        } else {
            $updateHistory =  array(
                'complete_time' => time()
            );

            if ($answer_right && $histroy['state'] == 0) {
                $updateHistory['state'] = 1;

                $user_integral = UserModel::where(['id' => $this->user_id])->select()->toArray();

                $update_intergral = array(
                    'integral' => $user_integral[0]['integral'] + 1
                );
                UserModel::where(['id' => $this->user_id])->update($update_intergral);
            }

            $res = HistoryModel::where(['active_id' => $activeId, 'user_id' => $this->user_id])->update($updateHistory);
        }

        if ($res) {
            $this->api_echo(200, '保存成功');
        } else {
            $this->api_echo(500, '保存失败');
        }
    }

    //获取所有活动
    public function getActiveList()
    {
        $return = array();

        $active_data = ActiveModel::field('id,activeName')->select();
        if (empty($active_data)) {
            $this->api_echo(100, '暂无活动数据');
        }

        if ($this->user_id == null) {
            $this->api_echo(100, '缺少参数,或请求方式错误');
        }

        $histroy_data = HistoryModel::where(['user_id' => $this->user_id])->field('active_id,complete_time,state')->order('id asc')->select()->each(function ($value) {
            $value['complete_time'] = date('m/d H:i:s', $value['complete_time']);
        });

        $user_points = UserModel::where(['id' => $this->user_id])->field('integral')->find();
        $return['activeList'] = $active_data;
        $return['historyList'] = $histroy_data;
        $return['userPoints'] = $user_points;
        $this->api_echo(200, '请求成功', $return);
    }

    //兑换奖品
    public function exchangeGift()
    {
        $socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
        
        if (!$socket) {
            $this->api_echo(102,'无法创建UDP套接字！');
        }

        $message = 'Hello UDP!';

        if (!socket_sendto($socket, $message, strlen($message), 0, '171.88.164.97', 8800)) {
            $this->api_echo(100,"无法发送数据: " . socket_strerror(socket_last_error()));
        }
        $this->api_echo(200,"数据已发送！" );

        // 关闭套接字
        socket_close($socket);
    }
}
